<template>
  <div>
    <Head @onHandler="onHeadHandler"></Head>
    <div class="container-wrapper">
      <sliderassembly />
      <div class="widget-container">
        <el-row
          style="flex: 1"
          class="pad-layout"
          :style="{ backgroundColor: pageSetup.bgColor, backgroundImage: 'url(' + pageSetup.bgImg + ')'}">
          <draggable
            class="list-row-group"
            @change="dragChange"
            @clone="dragStart"
            v-model="dataList"
            group="cc">
            <!-- 容器动态组件 -->
            <component
              v-if="dataList[0]"
              :list.sync="dataList[0].list"
              :splist.sync="dataList[0].list"
              :is="getContainerComponent(dataList[0].name)"
              :datas.sync="dataList"
              ref="ss"
              @activeCom="activeComponent">
              {{ dataList[0] }}
              <template #item="rlist">
                <div class="list-group-item item" v-for="(m, index) in rlist" :key="m.id">
                  <!-- <div :style="{ border: m.active ? '2px dashed black' : ''}"> {{ m.name }} {{ m.active }}</div> -->
                  <!--动态组件 -->
                  <div class="filed-wapper" v-if="m.setStyle">
                    <component
                      :is="getDefineAsyncComponent(m.name)"
                      :datas="m.setStyle"
                      :data-type="getComponentType(m.name)"
                      :style="{ border: m.active ? '3px dashed #00a0e9' : '', }"
                      @click.native="activeComponent(m, index)"
                      ref="pcom">
                    </component>
                    <div class="field-action" @click="removeComponent(m, index)" v-if="m.active">
                      <i class="el-icon-delete"></i>
                    </div>
                  </div>
                </div>
              </template>
            </component>
          </draggable>
        </el-row>
      </div>

      <div class="decorateAll" ref="leftNode">
        <transition name="decorateAnima" v-if="play">
          <el-tabs v-model="rightComp">
            <el-tab-pane label="页面设置" name="pageSetting">
              <decorate :datas="pageSetup"></decorate>
            </el-tab-pane>
            <el-tab-pane label="组件设置" name="compSetting">
              <!-- 路由缓存 -->
              <keep-alive exclude="richtextstyle">
                <!-- 动态组件 -->
                <component :is="rightcom" :datas.sync="currentproperties" @updateView="updateView" />
              </keep-alive>
            </el-tab-pane>
            <el-tab-pane label="容器设置" name="containSetting" v-if="dataList.length > 0">
              <Settting
                :datas.sync="dataList[0].setStyle"
                @updateList="updateList"
                @updateDataList="updateDataList"
                @deleteDataList="deleteDataList"
                @uploadInformation="uploadInformation">
              </Settting>
            </el-tab-pane>
          </el-tabs>
        </transition>
      </div>

      <!-- 点击容器 -->
      <div ref="btnNode" class="btnBox" @click="toggle" :title="title">
        <img v-if="play" src="../../assets/images/sq.png" class="imageBox" />
        <img v-else src="../../assets/images/sq.png" class="imageBox" />
      </div>

      <ConfrimDialog
        :pageformdata="pageformdata"
        :dialog-visible.sync="dialogFormVisible"
        @onSave="onSaveJson">
      </ConfrimDialog>
    </div>
  </div>
</template>
<script>
import utils from "@/utils/index";
import draggable from "vuedraggable";
import sliderassembly from "@/components/newSliderAssembly";
import { install } from "@/components/componentscom/lib";
import { installPadContainer } from "@/components/padContainer/lib";
import { installStyles } from "@/components/rightslider/lib";
import mixin from "@/components/padContainer/mixin";
import componentProperties from "@/utils/componentProperties"; // 组件数据
import Vue from "vue";
import Settting from "@/views/gridContainer/components/settting.vue";
import Head from "@/views/gridContainer/components/head.vue";
import ConfrimDialog from "./components/confrimDialog.vue";
let id = 1;
export default {
  components: {
    draggable,
    sliderassembly,
    Settting,
    ConfrimDialog,
    Head,
  },
  mixins: [mixin],
  data() {
    return {
      dataList: [
        {
          name: "singleContainer",
          list: [],
        },
      ],
      style: {},
      compProperties: componentProperties,
      newProps: [],
      rightComp: "compSetting",
      // 页面设置属性
      pageSetup: {
        pname: "",
        details: "",
        bgColor: "rgba(9, 9, 66, 1)",
        bottomLogo: {
          isShowBootom: false,
          botLogo: "",
        },
        isPerson: false,
        isBack: true,
        titleHeight: 35,
        bgImg: 'https://c.yjt361.com/appnass/v1/appshow/1713333499104',
        subjectCode: "",
        isShowTabbar: false
      },
      pageformdata: {
        id: "",
        name: "",
        note: "",
        pageId: "",
        pageContent: "",
      },
      dialogFormVisible: false,
      containerJson: {}, // 容器设置
      currentproperties: {}, // 当前组件属性属性
      rightcom: "", // 右侧组件切换
      play: true, //默认显示左侧容器
      title: "点击收起", //鼠标触摸提示文字
      comlist: []
    };
  },
  created() {
    install(Vue);
    installStyles(Vue);
    installPadContainer(Vue);
    this.dataList = [
      {
        setStyle: this.containerProperties.get("singleContainer"),
        list: [],
        name: "singleContainer",
      },
    ];
    this.getPageCustomDetail();
    localStorage.setItem('apptype',JSON.stringify(this.$route.query.appType));
  },
  watch: {
    dataList: {
      handler(val) {
        console.log("总数据监听---", val);
      },
      deep: true,
    },
  },
  mounted() {},
  computed: {
    getDefineAsyncComponent() {
      return function (name) {
        return this.compProperties.get(name) && this.compProperties.get(name).component;
      };
    },
    getContainerComponent(name) {
      return function (name) {  
        return name && this.containerProperties.get(name).component;
      };
    },
    getComponentType(name) {
      return function (name) {
        return this.compProperties.get(name) && this.compProperties.get(name).type;
      };
    },
    setDefineAsyncComponentConfigs(name) {
      return function (name) {
        return this.compProperties.get(name) && this.compProperties.get(name).setStyle;
        // this.getComponentOfName(name);
      };
    },
  },
  methods: {
    onHeadHandler(type) {
      switch (type) {
        case "cat":
          this.catJson();
          break;
        case "import":
          this.importJSON();
          break;
        case "export":
          this.exportJSON();
          break;
        case "back":
          this.$confirm("返回列表您添加或者修改的数据将会失效, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              // this.$router.go(-1);
              this.$router.push({
                path: '../pageMangent/pageList',
                query: {
                  protype: this.$route.query.appType
                }
              })
            })
            .catch(() => {});
          break;
        case "save":
          this.dialogFormVisible = true;
          break;
        default:
          break;
      }
    },
    onSaveJson() {
      this.savePageJson();
      this.$router.push({
        path: '../pageMangent/pageList',
        query: {
          protype: this.$route.query.appType
        }
      })
    },
    updateView() {
      console.log("updateView-----------", this.$refs);
      // this.$refs.pcom[0].onTextClick();
      // this.$refs.ss.$forceUpdate();
    },
    // 动态更新容器数量
    updateList(list, number) {
      const aa = this.dataList[0];
      if (aa.name === "mutiEquaContainer") {
        this.$refs.ss.changeContainerNumber(number);
      } else if(list === "add") {
        this.$refs.ss.updatedAddView(number);
      } else if(list === "edit") {
        this.$refs.ss.updatedEditView(number);
      } else if(list === "special") {
        this.$refs.ss.updatedSpecialAddView(number);
      } else if(list === "spedit") {
        this.$refs.ss.updatedSpecEditView();
      } else {
        this.$refs.ss.updatedView();
      }
    },
    updateDataList(deletobj) {
      this.$refs.ss.updatedDeleteView(deletobj);
    },
    deleteDataList(index) {
      this.$refs.ss.updatedDeleteList(index);
    },
    uploadInformation(imgObj) {
      this.$refs.ss.uploadInformation(imgObj);
    },
    getComponentOfName(name) {
      const comp = this.newProps.find((item) => name);
      if (comp) {
        return comp.value.compProperties;
      }
    },
    setFullBorderPadding(index) {
      return index === 0 ? "padding-left: 0" : index === this.dataList.length - 1 ? "padding-right: 0" : "";
    },
    dragChange(val) {
      console.log("dragChange-----", val);
      if (val.added) {
        const element = val.added.element;
        element.icon = undefined;
        element.setStyle = JSON.parse(
          JSON.stringify(this.containerProperties.get(element.name))
        );
        this.containerJson = this.containerProperties.get(element.name);
        this.dataList = [val.added.element];
      }
    },
    dragStart(val) {
      console.log("dragStart-----", val);
    },
    initDataList(count) {
      if (count < 0) {
        return;
      }
      this.dataList = [];
      for (let i = 0; i < count; i++) {
        this.dataList.push({
          list: [],
          group: i,
        });
      }
    },
    removeComponent(res, index) {
      this.recursiveDel(this.dataList, res);
    },
    activeComponent(res, index) {
      /* 替换 */
      // const aa = this.dataList[0];
      utils.forEach(this.dataList, (res, i) => {
        /* 修改选中 */
        this.recursiveTraverse(res, 0, (re, ii) => {
          if (re.active === true) {
            re.active = false;
          }
        });
      });
      res.active = true;
      this.rightcom = this.compProperties.get(res.name).style;
      this.currentproperties = res.setStyle;
      // 需要强制更新子组件
      this.$refs.ss.$forceUpdate();
    },
    // 递归遍历
    recursiveTraverse(node, index, action) {
      action(node, index);
      if (!node || !node.list || node.list.length === 0) {
        return;
      }
      node.list.forEach((item, index1) => {
        this.recursiveTraverse(item, index1, action);
      });
    },
    // 递归删除组件
    recursiveDel(arr, res) {
      arr.map((item, index) => {
        if (item.name === res.name && item.active) {
          arr.splice(index, 1);
        }
        if (item.list && item.list.length > 0) {
          item.list.map(ite => {
            if (ite.children) {
              ite.children.map(it => {
                this.comlist = it.list;
                this.recursiveDel(this.comlist, res);
              })
            } else {
              this.recursiveDel(item.list, res);
            }
          })
        }
      });
    },
    toggle() {
      this.play = !this.play;
      //通过点击事件判断play的样式
      if (this.play) {
        this.$refs.btnNode.style = "transform:rotate(360deg); right:22%; transition:0.3s";
        this.$refs.leftNode.style = "width:22%; transition:0.3s";
        this.title = "点击收起";
      } else {
        this.$refs.btnNode.style = "transform:rotate(180deg); left:0px; transition:0.3s";
        this.$refs.leftNode.style = "width:0px; transition:0.3s";
        this.title = "点击展开";
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    to.meta.keepAlive = true;  // 让 A 缓存，即不刷新
    next();
  }
};
</script>
<style lang="scss" scoped>
.pad-layout {
  margin: 0 auto;
  // max-width: 960px;
  max-width: 1080px;
  border-radius: 8px;
  box-shadow: 0 0 1px 5px #495060;
  // background: linear-gradient(125deg, #074335 0%, #0d5547 100%);
  box-sizing: border-box;
  background-size: 100% 100%;
  height: 100%;
  .padtop {
    width: 100%;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
  }
}

.widget-container {
  padding: 10px;
  // background: #f1f2f3;
  overflow-x: hidden;
  overflow-y: auto;
  // min-height: 667px;
  min-height: calc(100vh - 85px);
  flex: 1;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.filed-wapper {
  .field-action {
    position: absolute;
    //bottom: -24px;
    bottom: 0;
    right: -2px;
    height: 22px;
    line-height: 22px;
    // background: #409eff;
    z-index: 9;

    i {
      font-size: 22px;
      color: #fff;
      margin: 0 5px;
      cursor: pointer;
    }
  }
}

.container-wrapper {
  min-height: 800px;
  display: flex;
  width: 100%;

  .list-group {
    color: white;
    border: 1px #888888 dashed;
    text-align: center;
    height: 90%;
    cursor: pointer;
    min-height: calc(100vh - 100px);
    border-radius: 8px;
  }

  .list-group-item {
    position: relative;
  }

  .list-row-group {
    height: 90%;
  }

  .decorateAll {
    width: 376px;
    overflow-y: scroll;
    overflow-x: hidden;
    position: relative;
    padding: 0 12px;
    background: #fff;
  }
  /* 点击容器样式 */
  .btnBox {
    position: absolute;
    top: calc(50% - 40px);
    right: 3%;
    cursor: pointer;
    z-index: 999;
  }
  /* icon图片的样式 */
  .imageBox {
    width: 35px;
    height: 80px;
  }
}
</style>
<style lang="scss">
.container-wrapper {
  .el-row {
    height: 100% !important;
  }

  .el-col {
    height: 100%;
  }
}

.decorateAll {
  .el-tabs__content {
    height: calc(100vh - 150px) !important;
    overflow-y: auto;
  }
}

.jsonArea {
  width: 100%;
  height: 850px;
  overflow-y: auto;
  border: none;
  resize: none;
}

.JSONView {
  width: 80% !important;
  height: 1000px;
  /* overflow-y: scroll; */
}
</style>
